package com.kim.smartring.net.business;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONObject;

import android.content.Context;
import android.os.Bundle;

import com.kim.smartring.db.dao.HearRateRecordDao;
import com.kim.smartring.db.dao.SleepRecordDao;
import com.kim.smartring.db.dao.StepRecordDao;
import com.kim.smartring.db.dao.UserDao;
import com.kim.smartring.db.model.HeartRateRecord;
import com.kim.smartring.db.model.SleepRecord;
import com.kim.smartring.db.model.StepRecord;
import com.kim.smartring.db.model.User;
import com.kim.smartring.net.ACommunication;
import com.kim.smartring.net.AEntity;
import com.kim.smartring.net.IReceiverListener;
import com.kim.smartring.net.entity.SyncEntity;
import com.kim.smartring.net.entity.SyncEntity.SyncType;
import com.kim.smartring.net.impl.PostCommunication;

/**
 * 同步业务类
 * 
 * @author Huang
 * 
 */
public class SyncBusiness {

	public interface SyncCallback {
		void onSyncSuccess(SyncType syncType);

		void onSyncFail(SyncType syncType);
	}

	private static final String getCurrentUserAccount(Context context) {
		UserDao dao = new UserDao(context);
		List<User> users = dao.findAll(User.class);
		if (users != null && users.size() > 0) {
			return users.get(0).getAccount();
		}
		return null;
	}

	private static final String getCurrentUserUID(Context context) {
		// UserDao dao = new UserDao(context);
		// List<User> users = dao.findAll(User.class);
		// if (users != null && users.size() > 0) {
		// return users.get(0).getUserId();
		// }
		return "1401526122411";
	}

	/**
	 * 同步记步数据
	 * 
	 * @param context
	 */
	public static void syncStepInfo(final Context context,
			final SyncCallback callback) {
		String uid = getCurrentUserUID(context); // getCurrentUserAccount(context);
		StepRecordDao dao = new StepRecordDao(context);
		// TODO 测试数据
		final List<StepRecord> records = SyncUtils.syncStepsInfo(); // dao.getUnSyncStepRecords();
		final Bundle bundle = new Bundle();
		bundle.putSerializable("data", (Serializable) records);
		SyncEntity entity = new SyncEntity(context, SyncType.STEP,
				SyncEntity.generateSendDataStep(uid, records),
				new IReceiverListener() {

					@Override
					public void onReceive(AEntity entity) {
						processResult(context, bundle, SyncType.STEP, callback,
								entity.receiveData);
					}
				});
		final ACommunication comm = new PostCommunication(entity);
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					comm.sendEntity();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}).start();
	}

	/**
	 * 同步睡眠质量数据
	 * 
	 * @param context
	 */
	public static void syncSleepInfo(final Context context,
			final SyncCallback callback) {
		String uid = getCurrentUserUID(context); // getCurrentUserAccount(context);
		SleepRecordDao dao = new SleepRecordDao(context);
		final List<SleepRecord> records = SyncUtils.syncSleepQualityInfo(); // dao.getUnSyncSleepRecords();
		final Bundle bundle = new Bundle();
		bundle.putSerializable("data", (Serializable) records);
		SyncEntity entity = new SyncEntity(context, SyncType.SLEEP,
				SyncEntity.generateSendDataSleep(uid, records),
				new IReceiverListener() {

					@Override
					public void onReceive(AEntity entity) {
						processResult(context, bundle, SyncType.SLEEP,
								callback, entity.receiveData);
					}
				});
		final ACommunication comm = new PostCommunication(entity);
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					comm.sendEntity();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}).start();
	}

	/**
	 * 同步心率数据
	 * 
	 * @param context
	 */
	public static void syncHRInfo(final Context context,
			final SyncCallback callback) {
		String uid = getCurrentUserUID(context); // getCurrentUserAccount(context);
		HearRateRecordDao dao = new HearRateRecordDao(context);
		final List<HeartRateRecord> records = SyncUtils.syncHeartRateInfo();
		// (ArrayList<HeartRateRecord>) dao
		// .getUnSyncHeartRateRecords();
		final Bundle bundle = new Bundle();
		bundle.putSerializable("data", (Serializable) records);
		SyncEntity entity = new SyncEntity(context, SyncType.HEARTRATE,
				SyncEntity.generateSendDataHR(uid, records),
				new IReceiverListener() {

					@Override
					public void onReceive(AEntity entity) {
						processResult(context, bundle, SyncType.HEARTRATE,
								callback, entity.receiveData);
					}
				});
		final ACommunication comm = new PostCommunication(entity);
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					comm.sendEntity();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}).start();
	}

	@SuppressWarnings("unchecked")
	private static void processResult(Context context, Bundle bundle,
			SyncType syncType, SyncCallback callback, String receiveData) {
		JSONObject jsonObject = null;
		try {
			jsonObject = new JSONObject(receiveData);
			String msgcode = jsonObject.getString("msgcode");
			if ("0".equals(msgcode)) {
				callback.onSyncSuccess(syncType);
				switch (syncType) {
				case SLEEP:
					List<SleepRecord> sleepRecords = (List<SleepRecord>) bundle
							.getSerializable("data");
					SleepRecordDao sleepRecordDao = new SleepRecordDao(context);
					sleepRecordDao.updateSyncState(sleepRecords);
					sleepRecordDao = null;
					break;
				case STEP:
					List<StepRecord> stepRecords = (List<StepRecord>) bundle
							.getSerializable("data");
					StepRecordDao stepRecordDao = new StepRecordDao(context);
					stepRecordDao.updateSyncState(stepRecords);
					stepRecordDao = null;
					break;
				case HEARTRATE:
					List<HeartRateRecord> heartRateRecords = (List<HeartRateRecord>) bundle
							.getSerializable("data");
					HearRateRecordDao hearRateRecordDao = new HearRateRecordDao(
							context);
					hearRateRecordDao.updateSyncState(heartRateRecords);
					hearRateRecordDao = null;
					break;
				}
				return;
			}
			callback.onSyncFail(syncType);
		} catch (Exception e) {

		} finally {
			jsonObject = null;
		}
	}
}